<?php

namespace App\Services\Admin;

use App\Exceptions\LogicException;
use App\Models\Permission;

class PermissionService
{
    private $permissionModel;

    public function __construct(Permission $permissionModel)
    {
        $this->permissionModel = $permissionModel;
    }

    /**
     * 获取权限列表
     * @param array $params 查询参数
     * @return array
     */
    public function list(array $params): array
    {
        $fields = ['id', 'name', 'slug', 'module', 'description', 'created_at', 'updated_at'];
        $result = $this->permissionModel->list($params, $fields);

        $modules = config('modules');
        foreach ($result['items'] as $value) {
            $module = $value['module'];
            $value['module_text'] = $modules[$module] ?? $module;
        }
        return $result;
    }

    /**
     * 获取权限详情
     * @param int $id 权限ID
     * @return array
     * @throws LogicException
     */
    public function view(int $id): array
    {
        $fields = ['id', 'name', 'slug', 'module', 'description', 'created_at', 'updated_at'];
        $permission = $this->permissionModel->take(['id' => $id], $fields);
        if (empty($permission)) {
            throw new LogicException('权限不存在');
        }
        $modules = config('modules');
        $permission['module'] = $modules[$permission['module']] ?? $permission['module'];
        return $permission;
    }

    /**
     * 创建权限
     * @param array $data 权限数据
     * @return array
     * @throws LogicException
     */
    public function create(array $data): array
    {
        if ($this->permissionModel->take(['slug' => $data['slug'], 'module' => $data['module']], ['id'])) {
            throw new LogicException('权限标识已存在');
        }

        $id = $this->permissionModel->create($data);
        return ['id' => $id];
    }

    /**
     * 更新权限
     * @param int $id 权限ID
     * @param array $data 更新数据
     * @return array
     * @throws LogicException
     */
    public function update(int $id, array $data): array
    {
        if (!$this->permissionModel->take(['id' => $id], ['id'])) {
            throw new LogicException('权限不存在');
        }

        if (isset($data['slug'])) {
            $existingPermission = $this->permissionModel->take(['slug' => $data['slug'], 'module' => $data['module']], ['id']);
            if ($existingPermission && $existingPermission['id'] != $id) {
                throw new LogicException('权限标识已存在');
            }
        }

        $rows = $this->permissionModel->modify($id, $data);
        return ['affected_rows' => $rows];
    }

    /**
     * 删除权限
     * @param int $id 权限ID
     * @return array
     * @throws LogicException
     */
    public function delete(int $id): array
    {
        if (!$this->permissionModel->take(['id' => $id], ['id'])) {
            throw new LogicException('权限不存在');
        }
        $rows = $this->permissionModel->remove($id);
        return ['affected_rows' => $rows];
    }

    /**
     * 获取分组权限列表（用于权限选择组件）
     * @return array
     */
    public function getGroupedPermissions(): array
    {
        $fields = ['id', 'name', 'slug', 'module', 'description'];
        $permissions = $this->permissionModel->search(['order' => 'asc', 'sort' => 'id'], $fields);

        $modules = config('modules', []);
        $grouped = [];

        foreach ($permissions as $permission) {
            $module = $permission['module'];
            $moduleName = $modules[$module] ?? $module;

            if (!isset($grouped[$module])) {
                $grouped[$module] = [
                    'id' => $module,
                    'name' => $moduleName,
                    'children' => []
                ];
            }

            $grouped[$module]['children'][] = [
                'id' => $permission['id'],
                'name' => $permission['name'],
                'slug' => $permission['slug'],
                'description' => $permission['description']
            ];
        }

        return array_values($grouped);
    }

    /**
     * 从路由配置生成权限
     * @return array
     */
    public function generatePermissions(): array
    {
        $routeConfig = config('admin-routes');
        if (empty($routeConfig)) {
            throw new LogicException('路由配置不存在');
        }

        $effectNum = 0;

        foreach ($routeConfig as $routeKey => $route) {
            // 检查路由是否包含permission中间件
            $middleware = $route['middleware'] ?? [];
            if (!in_array('permission', $middleware)) {
                continue;
            }
            list($module, $slug) = explode('.', $routeKey);
            $description = $route['desc'] ?? '';

            // 检查权限是否已存在
            $existParams = [
                'module' => $module,
                'slug' => $slug,
            ];
            $existingPermission = $this->permissionModel->take($existParams, ['id']);
            if (!$existingPermission) {
                $addData = [
                    'name' => Permission::getPermissionName($slug),
                    'module' => $module,
                    'slug' => $slug,
                    'description' => $description,
                ];
                $this->permissionModel->create($addData);
                $effectNum += 1;
            }
        }

        return ['affected_rows' => $effectNum];
    }
}
